<?php

namespace Home\Controller;

class QueueController extends HomeController
{

    public function checkYichang()
    {
        $mo = M();
        $mo->execute('set autocommit=0');
        $mo->execute('lock tables hketrade_trade write');
        $Trade = M('Trade')->where('deal > num')
            ->order('id desc')
            ->find();

        if ($Trade) {
            if ($Trade['status'] == 0) {
                $mo->table('hketrade_trade')
                    ->where(array(
                        'id' => $Trade['id']
                    ))
                    ->save(array(
                        'deal' => Num($Trade['num']),
                        'status' => 1
                    ));
            } else {
                $mo->table('hketrade_trade')
                    ->where(array(
                        'id' => $Trade['id']
                    ))
                    ->save(array(
                        'deal' => Num($Trade['num'])
                    ));
            }

            $mo->execute('commit');
            $mo->execute('unlock tables');
        } else {
            $mo->execute('rollback');
            $mo->execute('unlock tables');
        }
    }



    public function qianbaoETH()
    {
        $coinList = M('Coin')->where(array(
            'status' => 1
        ))->select();

        $sum = 0;
        foreach ($coinList as $k => $v) {
            if ($v['type'] != 'eth') {
                echo 'eth';
                continue;
            }


            $coin = $v['name'];

            if (!$coin) {
                echo 'MM';
                continue;
            }

            $dj_address = $v['dj_zj'];
            $dj_port = $v['dj_dk'];

            echo 'start ' . $coin . "\n";

            $eth = new \Common\Ext\Ethereum($dj_address, $dj_port);
            if (!$eth->eth_protocolVersion()) {
                echo '钱包链接失败！';
                continue;
            }
            $listtransactions = $eth->listLocalTransactions($coin);
            echo 'listtransactions:' . count($listtransactions) . "\n";
            foreach ($listtransactions as $trans) {
                if (!$trans->to) {
                    echo 'empty to continue' . "<br>";
                    continue;
                }

                if ($user = M('UserCoin')->where(array(
                    $coin . 'b' => $trans->to
                ))->find()
                ) {
                    if (M('Myzr')->where(array(
                        'txid' => $trans->hash,
                        'status' => '1'
                    ))->find()
                    ) {
                        echo 'txid had found continue' . "<br>";
                        continue;
                    }
                    echo 'start receive do:' . "<br>";
                    $sfee = 0;
                    $true_amount = $eth->real_banlance($eth->decode_hex($trans->value));
                    $final_amount = $true_amount;
                    if ($v['zr_zs']) {
                        $song = round(($final_amount / 100) * $v['zr_zs'], 8);

                        if ($song) {
                            $sfee = $song;
                            $final_amount = $final_amount + $song;
                        }
                    }
                    if ($res = M('myzr')->where(array(
                        'txid' => $trans->hash
                    ))->find()
                    ) {
                        continue;
                    } else {
                        M('myzr')->add(array(
                            'userid' => $user['userid'],
                            'username' => $trans->to,
                            'coinname' => $coin,
                            'fee' => $sfee,
                            'txid' => $trans->hash,
                            'num' => $true_amount,
                            'mum' => $final_amount,
                            'addtime' => time(),
                            'status' => 0
                        ));
                        $zrflag = true;

                        // 到账转到主钱包
                        $transaction2 = new \Common\Ext\Ethereum_Transaction($trans->to, $v['dj_mian_address'], $eth->encode_dec($eth->to_real_value($true_amount - 0.001))); // 减去0.001作为手续费
                        $sendrs = $eth->eth_sendTransaction($trans->to, $user[$coin . 's'], $transaction2);
                    }
                    if ($zrflag) {
                        $mo = M();
                        $mo->execute('set autocommit=0');
                        $mo->execute('lock tables  hketrade_user_coin write , hketrade_myzr  write, hketrade_sms write,hketrade_config write ');
                        $rs = array();
                        $rs[] = $mo->table('hketrade_user_coin')
                            ->where(array(
                                'userid' => $user['userid']
                            ))
                            ->setInc($coin, $final_amount);
                        if ($res = $mo->table('hketrade_myzr')
                            ->where(array(
                                'txid' => $trans->hash
                            ))
                            ->find()
                        ) {
                            echo 'hketrade_myzr find and set status 1';
                            $rs[] = $mo->table('hketrade_myzr')->save(array(
                                'id' => $res['id'],
                                'addtime' => time(),
                                'status' => 1
                            ));
                        } else {
                            echo 'hketrade_myzr not find and add a new hketrade_myzr' . "\n";
                            $rs[] = $mo->table('hketrade_myzr')->add(array(
                                'userid' => $user['userid'],
                                'username' => $trans->to,
                                'coinname' => $coin,
                                'fee' => $sfee,
                                'txid' => $trans->hash,
                                'num' => $true_amount,
                                'mum' => $final_amount,
                                'addtime' => time(),
                                'status' => 1
                            ));
                        }

                        if (check_arr($rs)) {
                            $mo->execute('commit');
                            $mo->execute('unlock tables');
                            //D('Sms')->sendSmsFromConfig($user['moble'], 'myzr', $final_amount, $coin);
                            echo $final_amount . ' receive ok ' . $coin . ' ' . $final_amount . "<br>";
                            echo 'commit ok' . "\n" . "<br>";
                        } else {
                            echo $final_amount . 'receive fail ' . $coin . ' ' . $final_amount . "<br>";
                            echo var_export($rs, true);
                            $mo->execute('rollback');
                            $mo->execute('unlock tables');
                            print_r($rs);
                            echo 'rollback ok' . "\n" . "<br>";
                        }
                    }
                }

                if ($user = M('UserCoin')->where(array(
                    $coin . 'b' => $trans->from
                ))->find()
                ) {
                    echo 'start send do:' . "\n" . "<br>";
                    $myzc = M('Myzc')->where(array(
                        'txid' => $trans->hash
                    ))->find();

                    if ($myzc) {
                        if ($myzc['status'] == 0) {
                            M('Myzc')->where(array(
                                'txid' => $trans->hash
                            ))->save(array(
                                'status' => 1
                            ));
                            echo $eth->real_banlance(hexdec($trans->value)) . '成功转出' . $coin . ' 币确定' . "<br>";
                        }
                    }
                }
            }
        }
    }


    public function check_coldwallet()
    {
        $coinList = M('Coin')->where(array(
            'status' => 1
        ))->select();

        foreach ($coinList as $k => $v) {
            if ($v['type'] == 'rgb') {
                continue;
            }

            $coin = $v['name'];

            if (!$coin) {
                echo '币种错误';
                continue;
            }

            if ($v['cold_wallet'] != 1) {
                echo '未开启冷钱包功能';
                continue;
            }

            $dj_username = $v['dj_yh'];
            $dj_password = $v['dj_mm'];
            $dj_address = $v['dj_zj'];
            $dj_port = $v['dj_dk'];
            $dj_mian_address = $v['dj_mian_address'];
            $dj_mian_address_password = $v['dj_mian_address_password'];
            $cold_wallet_num = $v['cold_wallet_num'];
            $cold_wallet_address = $v['cold_wallet_address'];
            if ($v['type'] == 'qbb') {
                // 比特币核心钱包
                $CoinClient = CoinClient($dj_username, $dj_password, $dj_address, $dj_port, 5, array(), 1);
                $json = $CoinClient->getinfo();
                if (!isset($json['version']) || !$json['version']) {
                    echo $coin . '钱包链接失败！';
                    continue;
                }

                $balance = $json['balance'];
                if ($balance > $cold_wallet_num) {
                    $num = round($balance - $cold_wallet_num, 8);
                    $sendrs = $CoinClient->sendtoaddress($cold_wallet_address, $num);
                    if ($sendrs) {
                        $arr = json_decode($sendrs, true);
                        if (isset($arr['result']) && $arr['result'] != NULL) {
                            M('ColdWallet')->add(array(
                                'coin' => $coin,
                                'num' => $num,
                                'txid' => $arr['result'],
                                'address' => $cold_wallet_address
                            ));
                        }
                    }
                }
            } elseif ($v['type'] == 'peb') {
                $peb = new \Common\Ext\PuerClient($dj_address, $dj_port);
                if (!$peb->contencted()) {
                    echo $coin . '钱包链接失败！';
                    continue;
                }

                $balance = $peb->getBlance(dj_mian_address);

                if ($balance > $cold_wallet_num) {
                    $num = round($balance - $cold_wallet_num, 8);
                    $res = $peb->payRequest($dj_address, array(
                        'secret' => $dj_mian_address,
                        'source_account' => $dj_mian_address_password,
                        'value' => $num,
                        'currency' => $coin,
                        'destination_account' => $cold_wallet_address
                    ));
                    if ($res['success']) {
                        M('ColdWallet')->add(array(
                            'coin' => $coin,
                            'num' => $num,
                            'txid' => $res['hash'],
                            'address' => $cold_wallet_address
                        ));
                    }
                }
            } elseif ($v['type'] == 'eth') {
                $eth = new \Common\Ext\Ethereum($dj_address, $dj_port);
                if (!$eth->eth_protocolVersion()) {
                    echo $coin . '钱包链接失败！';
                    continue;
                }
                $balance = $eth->eth_getBalance($dj_mian_address);

                if ($balance > $cold_wallet_num) {
                    $num = round($balance - $cold_wallet_num, 8);

                    $transaction = new \Common\Ext\Ethereum_Transaction($dj_mian_address, $cold_wallet_address, $eth->encode_dec($eth->to_real_value((double)$num)));
                    $sendrs = $eth->eth_sendTransaction($dj_mian_address, $dj_mian_address_password, $transaction);
                    if ($sendrs) {
                        M('ColdWallet')->add(array(
                            'coin' => $coin,
                            'num' => $num,
                            'txid' => $sendrs,
                            'address' => $cold_wallet_address
                        ));
                    }
                    M('CodeCeshi')->setInc("num");
                }
            }
        }
    }

    public function qianbao()
    {
        $coinList = M('Coin')->where(array(
            'status' => 1
        ))->select();

        foreach ($coinList as $k => $v) {
            if ($v['type'] != 'qbb') {
                continue;
            }

            $coin = $v['name'];

            if (!$coin) {
                echo 'MM';
                continue;
            }

            $dj_username = $v['dj_yh'];
            $dj_password = $v['dj_mm'];
            $dj_address = $v['dj_zj'];
            $dj_port = $v['dj_dk'];
            echo 'start ' . $coin . "\n";
            $CoinClient = CoinClient($dj_username, $dj_password, $dj_address, $dj_port, 5, array(), 1);
            $json = $CoinClient->getinfo();
            //$data = $CoinClient->getblockcount();
            if (!isset($json['version']) || !$json['version']) {
                echo '###ERR#####***** ' . $coin . ' connect fail***** ####ERR####>' . "<br/>";
                continue;
            }

            echo 'Cmplx ' . $coin . ' start,connect ' . (empty($CoinClient) ? 'fail' : 'ok') . ' :' . "<br/>";
            $listtransactions = $CoinClient->listtransactions('*', 100, 0);
            echo 'listtransactions:' . count($listtransactions) . "<br/>";
            krsort($listtransactions);

            foreach ($listtransactions as $trans) {
                if (!$trans['account']) {
                    echo 'empty account continue' . "<br/>";
                    continue;
                }

                if (!($user = M('User')->where(array(
                    'username' => $trans['account']
                ))->find())
                ) {
                    echo 'no account find continue' . "<br/>";
                    continue;
                }

                if (M('Myzr')->where(array(
                    'txid' => $trans['txid'],
                    'status' => '1'
                ))->find()
                ) {
                    echo 'txid had found continue' . "<br/>";
                    continue;
                }

                echo 'all check ok ' . "<br/>";

                if ($trans['category'] == 'receive') {
                    print_r($trans);
                    echo 'start receive do:' . "<br/>";
                    $sfee = 0;
                    $true_amount = $trans['amount'];

                    if (C('Coin')[$coin]['zr_zs']) {
                        $song = round(($trans['amount'] / 100) * C('Coin')[$coin]['zr_zs'], 8);

                        if ($song) {
                            $sfee = $song;
                            $trans['amount'] = $trans['amount'] + $song;
                        }
                    }

                    if ($trans['confirmations'] < $v['zr_dz']) {
                        echo $trans['account'] . ' confirmations ' . $trans['confirmations'] . ' not elengh ' . C('Coin')[$coin]['zr_dz'] . ' continue ' . "<br/>";
                        echo 'confirmations <  c_zr_dz continue' . "<br/>";

                        if ($res = M('myzr')->where(array(
                            'txid' => $trans['txid']
                        ))->find()
                        ) {
                            M('myzr')->save(array(
                                'id' => $res['id'],
                                'addtime' => time(),
                                'status' => intval($trans['confirmations'] - C('Coin')[$coin]['zr_dz'])
                            ));
                        } else {
                            M('myzr')->add(array(
                                'userid' => $user['id'],
                                'username' => $trans['address'],
                                'coinname' => $coin,
                                'fee' => $sfee,
                                'txid' => $trans['txid'],
                                'num' => $true_amount,
                                'mum' => $trans['amount'],
                                'addtime' => time(),
                                'status' => intval($trans['confirmations'] - C('Coin')[$coin]['zr_dz'])
                            ));
                        }

                        continue;
                    } else {
                        echo 'confirmations full' . "<br/>";
                    }

                    $mo = M();
                    $mo->execute('set autocommit=0');
                    $mo->execute('lock tables  trade_user_coin  write , trade_myzr  write ');
                    $rs = array();
                    $rs[] = $mo->table('trade_user_coin')
                        ->where(array(
                            'userid' => $user['id']
                        ))
                        ->setInc($coin, $trans['amount']);

                    if ($res = $mo->table('trade_myzr')
                        ->where(array(
                            'txid' => $trans['txid']
                        ))
                        ->find()
                    ) {
                        echo 'trade_myzr find and set status 1';
                        $rs[] = $mo->table('trade_myzr')->save(array(
                            'id' => $res['id'],
                            'addtime' => time(),
                            'status' => 1
                        ));
                    } else {
                        echo 'trade_myzr not find and add a new trade_myzr' . "<br/>";
                        $rs[] = $mo->table('trade_myzr')->add(array(
                            'userid' => $user['id'],
                            'username' => $trans['address'],
                            'coinname' => $coin,
                            'fee' => $sfee,
                            'txid' => $trans['txid'],
                            'num' => $true_amount,
                            'mum' => $trans['amount'],
                            'addtime' => time(),
                            'status' => 1
                        ));
                    }

                    if (check_arr($rs)) {
                        $mo->execute('commit');
                        echo $trans['amount'] . ' receive ok ' . $coin . ' ' . $trans['amount'];
                        $mo->execute('unlock tables');
                        echo 'commit ok' . "<br/>";
                    } else {
                        echo $trans['amount'] . 'receive fail ' . $coin . ' ' . $trans['amount'];
                        echo var_export($rs, true);
                        $mo->execute('rollback');
                        $mo->execute('unlock tables');
                        print_r($rs);
                        echo 'rollback ok' . "<br/>";
                    }
                }
            }

            if ($trans['category'] == 'send') {
                echo 'start send do:' . "<br/>";

                if (3 <= $trans['confirmations']) {
                    $myzc = M('Myzc')->where(array(
                        'txid' => $trans['txid']
                    ))->find();

                    if ($myzc) {
                        if ($myzc['status'] == 0) {
                            M('Myzc')->where(array(
                                'txid' => $trans['txid']
                            ))->save(array(
                                'status' => 1
                            ));
                            echo $trans['amount'] . '成功转出' . $coin . ' 币确定';
                        }
                    }
                }
            }
        }
    }

    public function autoTrade(){
        $Coin = M('Coin')->where(array(
            'name' => 'bacc'
        ))->find();

        $dj_username = $Coin['dj_yh'];
        $dj_password = $Coin['dj_mm'];
        $dj_address = $Coin['dj_zj'];
        $dj_port = $Coin['dj_dk'];

        $CoinClient = CoinClient($dj_username, $dj_password, $dj_address, $dj_port, 5, array(), 1);
        $json = $CoinClient->getinfo();
        //$data = $CoinClient->getblockcount();
        if (!isset($json['version']) || !$json['version']) {
            echo '###ERR#####***** ' . 'bacc' . ' connect fail***** ####ERR####>' . "<br/>";
        }

        echo 'Cmplx ' . 'bacc' . ' start,connect ' . (empty($CoinClient) ? 'fail' : 'ok') . ' :' . "<br/>";

        $tradeData = M()->table('trade_trade as a')->field('a.id,a.userid,a.deal,b.btcb')->join('left join trade_user_coin as b on a.userid = b.userid')->where('a.type = 1 and a.order_status >= 3')->select();
        foreach ($tradeData as $k => $v) {
            $sendrs = $CoinClient->sendtoaddress($v['btcb'], floatval($v['deal']));
            $arr = json_decode($sendrs, true);
            if ($sendrs) {
                $rs = M('AutoTrade')->add(array(
                    'userid' => $v['userid'],
                    'trade_id' => $v['id'],
                    'num' => $v['num'],
                    'txid' => $arr['result']
                ));
            }
        }
        $makeTradeData = M()->table('trade_trade as a')->field('a.userid,a.deal,b.btcb')->join('left join trade_user_coin as b on a.userid = b.userid')->where('a.type = 2 and a.order_status >= 3')->select();
        foreach ($makeTradeData as $k => $v) {
            $sendrs = $CoinClient->sendtoaddress($v['btcb'], floatval($v['deal']));
            $arr = json_decode($sendrs, true);
            if ($sendrs) {
                $rs = M('AutoTrade')->add(array(
                    'userid' => $v['userid'],
                    'trade_id' => $v['id'],
                    'num' => $v['num'],
                    'txid' => $arr['result']
                ));
            }
            if (!$rs) {
                continue;
            }
        }
    }
}
